package com.witframework.datasource;
import java.sql.Connection;

import javax.sql.DataSource;

import com.witframework.core.WitFrameWork;

public class TestSmartPool{
	public TestSmartPool(){
		
	}
	static class  Counter{
		public static long time=0;
		public static long maxwaittime=0;
		public static int totalconn=0;
		public static int c = 0;//出错个数
		public static int threadnumber = 0;//某时刻需要处理的并发用户数		
	}
	class takeConn extends Thread {
		public takeConn(ThreadGroup tg,String name){
			super(tg,name);
		}
		private DataSource ds = (DataSource)WitFrameWork.getBean("dataSource");
		public void run () {
			int sleeptime = 1000; //事务长度 
			Counter.threadnumber ++;	
			long start=0;long ok;
			try {
				start=System.currentTimeMillis();
				Connection conn = ds.getConnection();
				conn.createStatement().execute("select * from ad_user");
				ok=System.currentTimeMillis()-start;
				Counter.time+=ok;
				if(ok>Counter.maxwaittime)
					Counter.maxwaittime=ok;							
				Thread.sleep(sleeptime);//模仿处理事务过程conn.close();
				//conn.close();				
			} catch (Exception e) {
				Counter.c ++;				
				e.printStackTrace();
			}
			Counter.threadnumber --;
			Counter.totalconn++;
			System.out.println ("task over ,Client = " + Counter.threadnumber+";total="+Counter.totalconn);
		}		
	}	
	private static void test(){
		long s=System.currentTimeMillis();
		ThreadGroup tg=new ThreadGroup("");
		int max = 0;
		long sleeptime =10;
		for (int i = 1; i <= 1000; i ++) {
			try {
				takeConn thread = new TestSmartPool().new takeConn(tg,"i");				
				thread.start ();
				//System.out.println ("Client = " + Counter.threadnumber);
				if (Counter.threadnumber > max) max = Counter.threadnumber;				
				Thread.sleep(sleeptime); //这里可以设置并发量,平均并发量理论值是1000/sleeptime
				while(tg.activeCount()>200)
					Thread.sleep(100); 
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		while(tg.activeCount()>1){			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {				
			}
		}
		System.out.println(System.currentTimeMillis()-s);
		System.out.println ("平均并发量理论值是 = " + (1000/sleeptime));
		System.out.println ("并发量波动范围：[" + (1000/sleeptime)+ "," + max + "]");
		System.out.println ("共 " + Counter.c + "个客户无法取得连接");
		System.out.println ("请求数 " + Counter.totalconn );		
		System.out.println ("最大等待时间 " + Counter.maxwaittime );
		System.out.println ("平均等待时间 " + Counter.time/Counter.totalconn );
	}
	
	
	public static void main(String args[]){		
		test();
	}
}



